<template>
    <div class="about">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="最后登录开始日期">
                <el-date-picker
                    v-model="formInline.lastLoginBeginTime"
                    type="datetime"
                    placeholder="选择开始日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="最后登录结束日期">
                <el-date-picker
                    v-model="formInline.lastLoginEndTime"
                    type="datetime"
                    default-time="23:59:59"
                    placeholder="选择结束日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="创建开始日期">
                <el-date-picker
                    v-model="formInline.beginTime"
                    type="datetime"
                    placeholder="选择开始日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="创建结束日期">
                <el-date-picker
                    v-model="formInline.endTime"
                    type="datetime"
                    default-time="23:59:59"
                    placeholder="选择结束日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="关键词">
                <el-input v-model="formInline.keyWords" clearable placeholder="模糊查询"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
        </el-form>
        <el-button
            style="float: right; margin-bottom: 10px"
            icon="el-icon-plus"
            type="primary"
            @click="onCreate"
            >新增用户</el-button
        >
        <el-table
            ref="filterTable"
            :data="tableData"
            :header-cell-style="{ color: '#606266', background: '#f5f7fa' }"
            style="width: 100%"
            stripe
            border
        >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column prop="name" label="姓名"> </el-table-column>
            <el-table-column prop="loginName" label="登录名"> </el-table-column>
            <el-table-column prop="phone" label="电话"> </el-table-column>
            <el-table-column prop="lastLoginTimeStr" label="最后登录时间">
            </el-table-column>
            <el-table-column prop="createdTimeStr" label="创建时间">
            </el-table-column>
            <el-table-column prop="modifiedTimeStr" label="修改时间">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                width="240"
            >
                <template slot-scope="scope">
                    <i  @click="handleEdit(scope.$index, scope.row)" class="el-icon-edit"></i>
                    <i  @click="handleDelete(scope.$index, scope.row)" class="el-icon-delete"></i>
                    <i  @click="handleLock(scope.$index, scope.row)" class="el-icon-lock"></i>
                    <i  @click="resetPwd(scope.$index, scope.row)" class="el-icon-refresh-right"></i>
                    <i  @click="seeJournal(scope.$index, scope.row)" class="el-icon-s-order"></i>
                    <i  @click="handleSetRole(scope.$index, scope.row)" class="el-icon-setting"></i>
                    <!-- <el-button
                        size="mini"
                        style="margin-bottom: 10px"
                        @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button
                    >
                    <el-button
                        size="mini"
                        style="margin-bottom: 10px"
                        v-if="scope.row.userID != user.userID"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button
                    >
                    <el-button
                        size="mini"
                        style="margin-bottom: 10px"
                        type="primary"
                        @click="handleLock(scope.$index, scope.row)"
                        >锁定</el-button
                    >
                    <el-button
                        size="mini"
                        style="margin-bottom: 10px"
                        type="success"
                        @click="resetPwd(scope.$index, scope.row)"
                        >重置密码</el-button
                    >
                    <el-button
                        size="mini"
                        style="margin-bottom: 10px"
                        type="warning"
                        @click="seeJournal(scope.$index, scope.row)"
                        >查看日志</el-button
                    >
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleSetRole(scope.$index, scope.row)"
                        >设置角色</el-button
                    > -->
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next"
                :current-page="currentPage"
                :page-size="pgSize"
                :total="total"
                :page-sizes="[1, 10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            ></el-pagination>
        </div>
        <!--    修改密码对话框-->
        <el-dialog
            title="重置密码"
            :visible.sync="dialogPasswordVisible"
            :close-on-click-modal="false"
            class="public-dialog-style"
        >
            <el-form
                ref="passwordForm"
                :rules="rules"
                :model="temp"
                label-position="left"
                label-width="100px"
            >
                <el-form-item label="登录密码" prop="loginPassword">
                    <el-input
                        v-model="temp.loginPassword"
                        placeholder="登录密码"
                        type="password"
                    />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input
                        v-model="temp.confirmPassword"
                        placeholder="确认密码"
                        type="password"
                    />
                </el-form-item>
            </el-form>
            <div class="dialog-footer">
                <el-button type="success" @click="updatePassword()"
                    >确定</el-button
                >
                <el-button @click="dialogPasswordVisible = false"
                    >取消</el-button
                >
            </div>
        </el-dialog>
        <el-dialog
            :title="type == 'add' ? '新增用户' : '编辑用户'"
            :visible.sync="editVisible"
            width="50%"
        >
            <el-form
                ref="ValidateForm"
                :model="form"
                label-width="80px"
                class="demo-form-inline dialog-form"
            >
                <el-form-item
                    label="姓名"
                    prop="name"
                    :rules="[
                        {
                            required: true,
                            message: '请输入姓名',
                            trigger: 'blur',
                        },
                    ]"
                >
                    <el-input
                        v-model="form.name"
                        prop="name"
                        placeholder="姓名"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="登录名"
                    prop="loginName"
                    :rules="[
                        {
                            required: true,
                            message: '请输入登录名',
                            trigger: 'blur',
                        },
                    ]"
                >
                    <el-input
                        v-model="form.loginName"
                        prop="loginName"
                        :readOnly="type == 'edit'"
                        placeholder="登录名"
                    ></el-input>
                </el-form-item>
                <el-form-item label="密码" v-if="type == 'add'">
                    <el-input
                        v-model="form.loginPwd"
                        placeholder="默认密码111111"
                        type="password"
                    ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" v-if="type == 'add'">
                    <el-input
                        v-model="form.loginNewPwd"
                        placeholder="默认密码111111"
                        type="password"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="手机"
                    prop="phone"
                    :rules="[
                        {
                            required: true,
                            message: '请输入手机号',
                            trigger: 'blur',
                        },
                        {
                            validator: validatorPhone,
                            message: '请输入正确的手机号',
                            trigger: ['blur', 'change'],
                        },
                    ]"
                >
                    <el-input
                        v-model="form.phone"
                        placeholder="手机"
                        type="tel"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
        <!--    设置角色对话框-->
        <el-dialog
            title="设置角色"
            :visible.sync="dialogRoleVisible"
            :close-on-click-modal="false"
            class="public-dialog-style"
        >
            <el-table
                v-loading="roleListLoading"
                :data="roleUserList"
                border
                fit
                highlight-current-row
            >
                <el-table-column
                    label="角色名称"
                    show-overflow-tooltip
                    prop="roleName"
                />
                <el-table-column
                    label="开始日期"
                    show-overflow-tooltip
                    prop="beginDate"
                />
                <el-table-column
                    label="结束日期"
                    show-overflow-tooltip
                    prop="endDate"
                />
                <el-table-column class-name="small-padding" label="操作" align="center" width="180">
                    <template slot-scope="{ row }">
                        <i  @click="handleUpdate(row)" class="el-icon-edit"></i>
                        <i  @click="handleDeletRoleUser(row)" class="el-icon-delete"></i>
                        <!-- <el-button
                            type="primary"
                            size="mini"
                            @click="handleUpdate(row)"
                            >编辑</el-button
                        >
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDeletRoleUser(row)"
                            >删除</el-button
                        > -->
                    </template>
                </el-table-column>
            </el-table>

            <el-divider>{{roleDialogStatus == 'add' ? '添加' : '编辑'}}角色</el-divider>

            <el-form
                ref="roleForm"
                :rules="roleRules"
                :model="temp"
                label-width="55px"
                :inline="true"
            >
                <el-form-item label="角色" prop="id" label-width="70px">
                    <el-select
                        v-model="temp.id"
                        class="filter-item"
                        clearable
                        placeholder="请选择角色"
                        @change="changeRole"
                    >
                        <el-option
                            v-for="item in this.roleList"
                            :key="item.id"
                            :label="item.name"
                            :value="roleDialogStatus == 'add' ? item.id : item.name"
                        />
                    </el-select>
                </el-form-item>
                <el-row>
                    <el-col :span="14">
                        <el-form-item label="选择日期" prop="beginDate" label-width="70px">
                            <el-date-picker
                                    v-model="temp.beginDate"
                                    type="datetime"
                                    placeholder="选择开始日期"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item prop="endDate">
                            <el-date-picker
                                    v-model="temp.endDate"
                                    type="datetime"
                                    default-time="23:59:59"
                                    placeholder="选择结束日期"
                                >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-button
                    type="success"
                    size="mini"
                    @click="createRoleUser"
                    style="float: right"
                    >确认</el-button
                >
            </el-form>
            <div class="dialog-footer">
                <el-button size="mini" @click="dialogRoleVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>


<script>
import { isNotEmpty } from "@/plugins";
import moment from "moment";
import { getToken, getItem } from "@/plugins/auth";
import Pagination from "@/components/Pagination";

export default {
    data() {
        return {
            currentPage: 1,
            dialogPasswordVisible: false,
            pgSize: 10,
            idx: -1,
            editVisible: false,
            form: {},
            outToken: localStorage.getItem("outToken"),
            formInline: {
                name: "",
                loginName: "",
                loginPwd: "",
                userID: "",
                phone: "",
                keyWords: '',
                companyName: "",
                lastLoginBeginTime: "",
                lastLoginEndTime: "",
                beginTime: "",
                endTime: "",
            },
            roleDialogStatus: 'addd',
            rolesForm: {
                name: "",
                shortName: "",
                beginDate: "",
                endDate: "",
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "名称不能为空",
                        trigger: "blur",
                    },
                ],
                loginName: [
                    {
                        required: true,
                        message: "登录名不能为空",
                        trigger: "blur",
                    },
                ],
                loginPassword: [
                    {
                        required: true,
                        message: "登录密码不能为空",
                        trigger: "blur",
                    },
                ],
                confirmPassword: [
                    {
                        required: true,
                        message: "确认密码不能为空",
                        trigger: "blur",
                    },
                ],
                roleID: [
                    {
                        required: true,
                        message: "角色不能为空",
                        trigger: "blur",
                    },
                ],
            },
            temp: {
                id: '',
                beginDate: '',
                endDate: ''
            },
            form: {
                name: "",
                loginName: "",
                loginPwd: "",
                loginNewPwd: "",
                phone: "",
            },
            tableData: [],
            total: 0,
            type: "add",
            user: {},
            dialogRoleVisible: false,
            roleListLoading: false,
            roleList: [],
            roleUserList: [],
            listRoleQuery: {
                token: getToken(),
                currentPage: 1,
                pageNumber: 10,
                userID: "",
            },
            roleRules: {
                id: [
                    {
                        required: true,
                        message: "角色不能为空",
                        trigger: "blur",
                    },
                ],
            },
            totalRole: 0,
        };
    },
    components: {
        Pagination,
    },
    mounted() {
        this.user =
            (getItem("userInfo") &&
                JSON.parse(decodeURIComponent(getItem("userInfo")))) ||
            {};
        this.initPage();
    },
    methods: {
        handleLoginTime(data) {},
        handleCreatedTime(data) {},
        handleDeletRoleUser(row) {
            this.$confirm("是否确认删除 " + row.name + "?", {
                type: "warning",
                closeOnClickModal: false, // 点击区域外不可关闭
                closeOnPressEscape: false, // 按ESC不可关闭
            }).then(() => {
                let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemDeleteOneRoleUser.json?outToken=${getToken()}&roleUserID=${
                    row.id
                }`;
                this.axios(url).then((res) => {
                    this.$notify({
                        title: "成功",
                        message: "删除成功",
                        type: "success",
                        duration: 2000,
                    });
                    this.getRoleUserList();
                });
            });
        },
        handleUpdate(row) {
            this.roleDialogStatus = 'edit'
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemGetRoleUserDetail.json?roleUserID=${row.id}&outToken=${getToken()}`;
            this.axios(url).then((res) => {
                let data = res.body.data, ex;
                this.temp = data
                ex = this.temp.id
                this.temp.id = this.temp.name
                this.temp.name = ex
            });
            // const params = { token: getToken(), ID: row.ID }
            // fetchUserOne(params).then(response => {
            //     this.temp = response.body.data
            //     this.temp.approvedTime = (isNotEmpty(this.temp.approvedTime) ? moment(this.temp.approvedTime).format('YYYY-MM-DD HH:mm:ss') : '')
            //     this.temp.lastLoginTime = (isNotEmpty(this.temp.lastLoginTime) ? moment(this.temp.lastLoginTime).format('YYYY-MM-DD HH:mm:ss') : '')
            //     this.dialogStatus = 'update'
            //     this.dialogFormVisible = true
            //     this.disableEdit = true
            //     this.$nextTick(() => {
            //         this.$refs['dataForm'].clearValidate()
            //     })
            // })
        },
        createRoleUser() {
            let { beginDate, endDate } =
                this.temp;
            beginDate = isNotEmpty(beginDate)
                ? moment(beginDate).format("YYYY-MM-DD HH:mm:ss")
                : "";
            endDate = isNotEmpty(endDate)
                ? moment(endDate).format("YYYY-MM-DD HH:mm:ss")
                : "";
            let str = `&beginDate=${beginDate}&endDate=${endDate}`
            this.$refs["roleForm"].validate((valid) => {
                if (valid) {
                    if (this.roleDialogStatus == 'edit') {
                        let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemUpdateOneRoleUser.json?outToken=${getToken()}&roleID=${
                            this.temp.roleID
                        }&roleUserID=${this.temp.name}&name=${this.temp?.newName}${str}`;
                        this.axios(url).then((res) => {
                            this.getRoleUserList()
                            this.$notify({
                                title: "编辑成功",
                                message: "角色编辑成功",
                                type: "success",
                                duration: 2000,
                            });
                            
                            this.$nextTick(() => {
                                this.$refs['roleForm'].resetFields()
                            })
                        });
                    } else {
                        this.roleList.forEach(v=>{
                            if (v.id == this.temp.id) {
                                this.temp.shortName = v.name
                            }
                        })
                        console.log(this.temp.id,'temp');
                        let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemCreatedOneRoleUser.json?outToken=${getToken()}&roleID=${
                            this.temp.id
                        }&userID=${this.temp.userID}&companyID=${this.user.companyID}&name=${this.temp.shortName}${str}`;
                        this.axios(url).then((res) => {
                            this.getRoleUserList()
                            this.$notify({
                                title: "创建成功",
                                message: "角色创建成功",
                                type: "success",
                                duration: 2000,
                            });
                            this.$nextTick(() => {
                                this.$refs['roleForm'].resetFields()
                            })
                        });
                    }
                }
            });
        },
        handleLock() {},
        seeJournal() {},
        resetPwd(index, row) {
            // this.dialogStatus = 'password'
            // this.dialogPasswordVisible = true
            // this.temp.loginPassword = ''
            this.temp.userID = row.userID;
            // this.$nextTick(() => {
            //     this.$refs['passwordForm'].clearValidate()
            // })
            this.updatePassword();
        },
        setRule() {},
        validatorPhone(rule, value, callback) {
            if (value === "") {
                callback(new Error("手机号不能为空"));
            } else if (!/^1\d{10}$/.test(value)) {
                callback(new Error("手机号格式错误"));
            } else {
                callback();
            }
        },
        updatePassword() {
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemResetOneUserPassword.json?outToken=${getToken()}&userID=${
                this.temp.userID
            }`;
            this.axios(url).then((res) => {
                this.$notify({
                    title: "成功",
                    message: "重置密码成功",
                    type: "success",
                    duration: 2000,
                });
            });
        },
        initPage() {
            let { beginTime, endTime, lastLoginBeginTime, lastLoginEndTime,keyWords } =
                this.formInline;
            beginTime = isNotEmpty(beginTime)
                ? moment(beginTime).format("YYYY-MM-DD HH:mm:ss")
                : "";
            endTime = isNotEmpty(endTime)
                ? moment(endTime).format("YYYY-MM-DD HH:mm:ss")
                : "";
            lastLoginBeginTime = isNotEmpty(lastLoginBeginTime)
                ? moment(lastLoginBeginTime).format("YYYY-MM-DD HH:mm:ss")
                : "";
            lastLoginEndTime = isNotEmpty(lastLoginEndTime)
                ? moment(lastLoginEndTime).format("YYYY-MM-DD HH:mm:ss")
                : "";
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemGetOneUserList.json?&outToken=${getToken()}&companyID=${this.user.companyID}&beginTime=${beginTime}&endTime=${endTime}&lastLoginBeginTime=${lastLoginBeginTime}&lastLoginEndTime=${lastLoginEndTime}&currentPage=${
                this.currentPage
            }&pageNumber=${this.pgSize}&keyWords=${keyWords}`;
            this.axios(url).then((res) => {
                let data = res?.body?.data?.rows;
                if (data.length == 0) {
                    if (this.currentPage > 1) {
                        this.currentPage--;
                        this.initPage();
                    }
                }
                this.tableData = res?.body?.data?.rows || [];
                this.currentPage = res?.body?.data?.currentPage;
                this.total = res?.body?.data?.total;
            });
        },
        onSubmit() {
            this.currentPage = 1;
            this.pgSize = 10;
            this.initPage();
        },
        getRandom() {
            let rand = "";
            for (let index = 0; index < 8; index++) {
                rand += index;
            }
            return rand;
        },
        createUser() {
            if (this.form.loginPwd === this.form.loginNewPwd) {
                let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemCreateOneUser.json?&outToken=${getToken()}&outUserID=${this.getRandom()}&name=${
                    this.form.name
                }&phone=${this.form.phone}&loginName=${
                    this.form.loginName
                }&loginPassword=${
                    this.form.loginPwd || 111111
                }&code=4444&companyID=${this.user.companyID}`;
                this.axios(url).then((res) => {
                    this.$message.success(`新增用户成功`);
                    this.editVisible = false;
                    this.initPage();
                });
            } else {
                this.$message.error("两次密码不一致 请重新输入");
            }
        },
        onCreate() {
            this.type = "add";
            this.editVisible = true;
        },
        handleEdit(index, row) {
            this.idx = index;
            this.type = "edit";
            this.form = row;
            this.editVisible = true;
        },
        saveEdit() {
            this.$refs["ValidateForm"].validate((valid) => {
                if (valid) {
                    if (this.type == "edit") {
                        this.editUser();
                    } else {
                        this.createUser();
                    }
                } else {
                    return false;
                }
            });
        },
        editUser() {
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemUpdateOneUser.json?&outToken=${getToken()}&userID=${
                this.form.userID
            }&name=${this.form.name}&phone=${this.form.phone}&loginName=${
                this.form.loginName
            }&loginPassword=${this.form.loginPassword}&code=${
                this.form.code
            }&companyID=${this.form.companyID}&companyName=${
                this.form.companyName
            }`;
            this.axios(url).then((res) => {
                this.initPage();
                this.editVisible = false;
                this.$message.success(`修改成功`);
            });
        },
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm("确定要删除吗？", "提示", {
                type: "warning",
            })
                .then(() => {
                    let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemDeleteOneUser.json?&outToken=${getToken()}&userID=${
                        row.userID
                    }`;
                    this.axios(url).then((res) => {
                        this.$message.success("删除成功");
                        this.initPage();
                    });
                })
                .catch(() => {});
        },
        handleSetRole(index, row) {
            this.temp.beginDate = ''
            this.temp.endDate = ''
            this.temp.name = ''
            this.temp.id = ''
            this.roleDialogStatus = 'add'
            // 获取角色列表
            let systemDefineID = getItem("systemDefineID");
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemGetRoleList.json?outToken=${getToken()}&systemDefineID=${systemDefineID}`;
            this.axios(url).then((res) => {
                this.roleList = res.body.data.rows;
            });
            let url1 = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemGetRoleUserList.json?outToken=${getToken()}&userID=${row.userID}`;
            this.axios(url1).then((res) => {
                this.dialogRoleVisible = true;
                // this.$refs['roleForm'].resetFields()
                this.roleUserList = res.body.data.rows;
                this.totalRole = res.body.data.total;
            });
            this.temp.userID = row.userID;
        },
        changeRole (data) {
            this.temp.newName = data
        },
        // 获取当前用户角色
        getRoleUserList() {
            this.roleListLoading = true;
            this.listRoleQuery.resultArray = "ID,name,role.roleID.name";
            let url = `https://kpinterface.shejidedao.cn/interface-server/api/outSystemGetRoleUserList.json?outToken=${getToken()}&userID=${this.temp.userID}`;
            this.axios(url).then((res) => {
                this.roleUserList = res.body.data.rows;
                this.totalRole = res.body.data.total;
                this.roleListLoading = false;
            });
        },
        handlePageChange(val) {
            this.currentPage = val;
            this.initPage();
        },
        handleSizeChange(val) {
            this.pgSize = val;
            this.initPage();
        },
        resetDateFilter() {
            this.$refs.filterTable.clearFilter("date");
        },
        clearFilter() {
            this.$refs.filterTable.clearFilter();
        },
        formatter(row, column) {
            return row.address;
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        filterHandler(value, row, column) {
            const property = column["property"];
            return row[property] === value;
        },
    },
};
</script>

<style lang="scss" scoped>
.img {
    width: 40px;
    height: 40px;
}

.pagination {
    margin: 20px 0;
    text-align: right;
}
.dialog-form {
    .el-input {
        width: 80% !important;
    }
}

</style>
<style>
.customWidth {
    width: 600px;
}
.el-scrollbar__wrap {
    overflow-x: hidden;
}
.about .public-dialog-style .el-dialog{
    width: 600px !important;
}
.about .small-padding i {
    font-size: 20px;
    margin-right: 10px;
    cursor: pointer;
}

</style>